import axios from 'axios'
import MXR from '../common/encryption'
import {
  Message,
  Loading
} from 'element-ui'

const instance = axios.create({
  timeout: 5000
})

const SIGN = process.env.SIGN
const APP_ID = process.env.APP_ID

let pending = []
let cancelToken = axios.CancelToken

let removePending = config => {

  // console.log('pending', pending)

  for (let p in pending) {

    if (pending[p].u === config.url.split('?')[0] + '&' + config.method) {

      //当当前请求在数组中存在时执行函数体
      pending[p].f(); //执行取消操作
      pending.splice(p, 1); //数组移除当前请求

    }
  }
}

function errorMsg() {

  return Message.error({
    message: '网络异常',
    duration: 1500
  })
}

instance.interceptors.request.use(function (config) {

  removePending(config); //在一个axios发送前执行一下取消操作

  config.cancelToken = new cancelToken((c) => {
    // pending存放每一次请求的标识，一般是url + 参数名 + 请求方法，当然你可以自己定义
    pending.push({
      u: config.url.split('?')[0] + '&' + config.method,
      f: c
    }); //config.data为请求参数
  });


  if (config.method === 'get' || config.method === 'delete') {
    // config.params['sign'] = SIGN
    // config.params['appId'] = APP_ID
  } else if (config.method === 'post') {
    // config.data['sign'] = SIGN
    // config.data['appId'] = APP_ID
  }

  return config;

}, function (error) {

  return Promise.reject(error);

});


export default {
  get(method) {
    instance.get(method.url, {
      params: method.data || {},
      headers: {
        'mxr-key': localStorage.getItem('mxr-key') || '',
        'Content-Type': 'application/json'
      }
    }).then(function (response) {
      if (response.status === 200) {
        if (response.data.Header.ErrCode === 0) {
          if (method.encryption && response.data.Body) {
            let str = response.data.Body
            let json = Convert2JSON(MXR.decryptionMxr(str))
            method.success(json)
          } else {
            method.success(response.data.Body)
          }
        } else {
          if (method.fail != null) {
            method.fail(response.data.Header)
          }

        }
      } else {

        if (method.error != null) {
          method.error()
        }
      }
    }).catch(function (e) {

      if (axios.isCancel(e)) {

        console.log('Request canceled', e.message);

      } else {

        // errorMsg()

        if (method.error != null) {

          method.error(e)

        }
      }
    })
  },

  delete(method) {
    instance.delete(method.url, {
      params: method.data || {},
      headers: {
        'mxr-key': localStorage.getItem('mxr-key') || '',
        'Content-Type': 'application/json'
      }
    }).then(function (response) {
      if (response.status === 200) {
        if (response.data.Header.ErrCode === 0) {
          if (method.encryption) {
            let str = response.data.Body
            let json = Convert2JSON(MXR.decryptionMxr(str))
            method.success(json)
          } else {
            method.success(response.data.Body)
          }
        } else {
          if (method.fail != null) {
            method.fail(response.data.Header)
          }
        }
      } else {
        if (method.error != null) {
          method.error()
        }
      }
    }).catch(function (e) {
      // errorMsg()
      console.error(e)
      if (method.error != null) {
        method.error(e)
      }
    })
  },

  post(method) {
    const loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    instance.post(method.url, method.data, {
        headers: {
          'mxr-key': localStorage.getItem('mxr-key') || '',
          'Content-Type': 'application/json'
        }
      })
      .then((response) => {
        console.log(response)
        if (response.status !== 200) {
          // errorMsg()
        } else {
          if (response.data.Header.ErrCode !== 0) {
            if (method.fail != null) {
              method.fail(response.data.Header)
            }
          } else {
            method.success(response.data.Body)
          }
        }
      }).catch((e) => {
        console.error(e)
        // errorMsg()
      }).finally((e) => {
        loading.close();
      })
  },

  postFormData(method) {
    const loading = Loading.service({
      lock: true,
      text: 'Loading',
      spinner: 'el-icon-loading',
      background: 'rgba(0, 0, 0, 0.7)'
    })
    instance.post(method.url, method.data, {
        headers: {
          'Accept': '*/*',
          'Content-Type': 'application/x-www-form-urlencoded'
        },
        transformRequest: [function (data) {
          let ret = ''
          for (let it in data) {
            ret += encodeURIComponent(it) + '=' + encodeURIComponent(data[it]) + '&'
          }
          return ret.substring(0, ret.length - 1)
        }]
      })
      .then(function (response) {
        if (response.status !== 200) {
          // errorMsg()
        } else {
          if (response.data.Header.ErrCode !== 0) {
            if (method.fail != null) {
              method.fail(response.data.Header)
            }
          } else {
            method.success(response.data.Body)
          }
        }
      }).catch(function (e) {
        // errorMsg()
      }).finally(function (e) {
        loading.close();
      })
  }
}

function Convert2JSON(str) {
  try {
    return JSON.parse(str)
  } catch (e) {
    return str
  }
}
